package com.jinzecloud.reportapproval.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinzecloud.reportapproval.bean.SampleDetails;
import com.jinzecloud.reportapproval.bean.SampleInspection;
import com.jinzecloud.reportapproval.bean.SampleSheet;
import com.jinzecloud.reportapproval.bean.SampleSheetWorkplaceDetail;
import com.jinzecloud.reportapproval.dto.AuditParam;
import com.jinzecloud.reportapproval.dto.DataStagingParam;
import com.jinzecloud.reportapproval.enums.StateEnum;
import com.jinzecloud.reportapproval.service.AdminService;
import com.jinzecloud.reportapproval.service.SampleDetailsService;
import com.jinzecloud.reportapproval.service.SampleInspectionService;
import com.jinzecloud.reportapproval.service.SampleSheetWorkplaceDetailService;
import com.jinzecloud.reportapproval.utils.R;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;


/**
 * 验样单
 *
 * @author æ­å°
 * @email 1971240051@qq.com
 * @date 2024-12-03 16:18:45
 */
@RestController
@RequestMapping("/sampleInspection")
@RequiredArgsConstructor
public class SampleInspectionController {

    private final SampleInspectionService sampleInspectionService;
    private final SampleDetailsService sampleDetailsService;
    private final SampleSheetWorkplaceDetailService sampleSheetWorkplaceDetailService;
    private final AdminService adminService;
    @PostMapping
    public R save(@RequestBody SampleInspection sampleInspection) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        sampleInspection.setState(StateEnum.UN_SUBMIT.getState()).setWordPath("").setPdfPath("");
        sampleInspection.setCreatedUserId(adminService.getIdByName(authentication.getName()));
        R r = sampleInspectionService.saveSampleInspection(sampleInspection);
        if (CollectionUtil.isNotEmpty(sampleInspection.getSampleDetailsList())) {
            sampleInspection.getSampleDetailsList().forEach(item -> item.setSampleInspectionId(sampleInspection.getId()));
            sampleDetailsService.saveBatch(sampleInspection.getSampleDetailsList());
        }
        if (CollectionUtil.isNotEmpty(sampleInspection.getSampleInspectionWorkplaceDetailList())) {
            sampleInspection.getSampleInspectionWorkplaceDetailList().forEach(item -> item.setSampleInspectionId(sampleInspection.getId()));
            sampleSheetWorkplaceDetailService.saveBatch(sampleInspection.getSampleInspectionWorkplaceDetailList());
        }
        return r;
    }

    @PutMapping
    public R update(@RequestBody SampleInspection sampleInspection) {
        sampleInspection.setState(StateEnum.UN_SUBMIT.getState()).setWordPath("").setPdfPath("");
        sampleInspectionService.updateById(sampleInspection);
        if (CollectionUtil.isNotEmpty(sampleInspection.getSampleDetailsList())) {
            sampleDetailsService.remove(new LambdaQueryWrapper<SampleDetails>().eq(SampleDetails::getSampleInspectionId, sampleInspection.getId()));
            sampleInspection.getSampleDetailsList().forEach(item -> item.setSampleInspectionId(sampleInspection.getId()));
            sampleDetailsService.saveBatch(sampleInspection.getSampleDetailsList());
        }
        if (CollectionUtil.isNotEmpty(sampleInspection.getSampleInspectionWorkplaceDetailList())) {
            sampleSheetWorkplaceDetailService.remove(new LambdaQueryWrapper<SampleSheetWorkplaceDetail>().eq(SampleSheetWorkplaceDetail::getSampleInspectionId, sampleInspection.getId()));
            sampleInspection.getSampleInspectionWorkplaceDetailList().forEach(item -> item.setSampleInspectionId(sampleInspection.getId()));
            sampleSheetWorkplaceDetailService.saveBatch(sampleInspection.getSampleInspectionWorkplaceDetailList());
        }
        return R.ok();
    }

    @PostMapping("/review")
    public R review(@RequestBody SampleSheet sampleSheet) {
        sampleInspectionService.updateById(new SampleInspection().setId(sampleSheet.getId()).setState(0));
        return R.ok();
    }

    @PostMapping("/audit")
    public R audit(@RequestBody AuditParam auditParam) {
        return sampleInspectionService.audit(auditParam);
    }

    @PostMapping("/list")
    public R list(@RequestBody DataStagingParam param) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LambdaQueryWrapper<SampleInspection> sampleInspectionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sampleInspectionLambdaQueryWrapper.and(w -> w.ne(SampleInspection::getState, StateEnum.APPROVAL_PASS.getState()).eq(SampleInspection::getCreatedUserId, adminService.getIdByName(authentication.getName())
        ).or().eq(SampleInspection::getState, StateEnum.UN_SUBMIT.getState()));
        if (!StringUtils.isBlank(param.getSearchKey())){
            sampleInspectionLambdaQueryWrapper.and(w -> w.like(SampleInspection::getProjectCode, param.getSearchKey())
                    .or().like(SampleInspection::getPrototypeTrademark, param.getSearchKey()));
        }
        Page<SampleInspection> page = sampleInspectionService.page(new Page<>(param.getPageNo(), param.getPageSize()),
                sampleInspectionLambdaQueryWrapper
        );
        return R.ok().setData(page);
    }

    @PostMapping("/auditList")
    public R auditList(@RequestBody DataStagingParam param) {
        return R.ok().setData(sampleInspectionService.auditList(param));
    }

    @GetMapping("/getByProjectCode/{projectCode}")
    public R getByProjectCode(@PathVariable String projectCode) {
        SampleInspection sampleInspection = sampleInspectionService.getOne(new LambdaQueryWrapper<SampleInspection>().eq(SampleInspection::getProjectCode, projectCode));
        Integer id = sampleInspection != null ? sampleInspection.getId() : null;
        return R.ok().setData(id == null ? null : sampleInspectionService.getById(id)
                .setSampleDetailsList(sampleDetailsService.list(new LambdaQueryWrapper<SampleDetails>().eq(SampleDetails::getSampleInspectionId, id)))
                .setSampleInspectionWorkplaceDetailList(sampleSheetWorkplaceDetailService.list(new LambdaQueryWrapper<SampleSheetWorkplaceDetail>().eq(SampleSheetWorkplaceDetail::getSampleInspectionId, id)))
        );
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        return R.ok().setData(sampleInspectionService.getById(id)
                .setSampleDetailsList(sampleDetailsService.list(new LambdaQueryWrapper<SampleDetails>().eq(SampleDetails::getSampleInspectionId, id)))
                .setSampleInspectionWorkplaceDetailList(sampleSheetWorkplaceDetailService.list(new LambdaQueryWrapper<SampleSheetWorkplaceDetail>().eq(SampleSheetWorkplaceDetail::getSampleInspectionId, id)))
        );
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long id) {
        sampleInspectionService.removeById(id);
        return R.ok();
    }

    @PostMapping("/batchDelete")
    public R batchDelete(@RequestBody Long[] ids) {
        sampleInspectionService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    @GetMapping("/getFilePath/{id}")
    public R getReportFilePath(@PathVariable("id") String id, HttpServletRequest request) throws IOException, IllegalAccessException {
        String path = sampleInspectionService.getReportFilePath(id, request);
        return R.ok().put("path", path);
    }

    @RequestMapping("/viewPdf/{id}")
    public String viewPdf(@PathVariable("id") Integer id){
        return sampleInspectionService.viewPdf(id);
    }

    @RequestMapping("/viewWord/{id}")
    public String viewWord(@PathVariable("id") Integer id){
        return sampleInspectionService.viewWord(id);
    }

}
